/****************************************************
          File Name:48-1-writer.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 16 Sep 2014 07:20:45 PM CST
*****************************************************/

#include "svshm_xfr.h"
#include <string.h>

int
main(int argc, char *argv[])
{
    int bytes, xfrs,cnt,fd;
	void *addr;
	int semid;
	union sem dummy;
	
	semid=semget(SEM_KEY,2,IPC_CREAT|PERM);
	if(semid==-1)
		err("semget");
	
	if(Available(semid,WRITE_SEM)==-1)
		err("init semavailable");
	if(Inuse(semid,READ_SEM)==-1)
		err("init seminuse");

	/**********  fd  ************/
	if((fd=open(PATH,O_CREAT|O_RDWR,00644))==-1)
		err("open/creat file");
	if(ftruncate(fd,LEN)==-1)
		err("making empty file");
	/***********	end		************/
	
   addr = mmap(NULL, LEN, PROT_WRITE,MAP_SHARED,fd,0);
    if (addr == MAP_FAILED)
        err("mmap");

    for (xfrs = 0, bytes = 0; ; xfrs++, bytes += cnt)
    {
		if(reserve(semid,WRITE_SEM)==-1)
			err("reserve");
/* clean the underlying file */
		memset(addr,0,LEN);
		
        cnt = read(STDIN_FILENO, addr, LEN);
        if (cnt == -1)
            err("read");
 /* the following two lines: sync to fd, then reader can read the changes from fd, this is the key to mmap ipc */
		if(msync(addr,LEN,MS_SYNC)==-1)
			err("msync");
		
		if(release(semid,READ_SEM)==-1)
			err("release");
		
        if (cnt == 0)
            break;
    }

	if(reserve(semid,WRITE_SEM)==-1)
		err("final reserve");
	
	if(semctl(semid,0,IPC_RMID,dummy)==-1)
		err("semctl");

	if(munmap(addr,LEN)==-1)
		err("munmap");

    fprintf(stderr, "Sent %d bytes (%d xfrs)\n", bytes, xfrs);
    exit(EXIT_SUCCESS);
}
